package com.tanhua.app.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.exception.ErrorResult;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CommentsService {
    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private UserFreezeService userFreezeService;

    //获取评论列表
    public PageResult<CommentVo> comments(String movementId, Integer page, Integer pagesize) {
        //根据movementId查询comment表获取所有评论
        List<Comment> commentList=commentApi.findPagesByMovementId(movementId, CommentType.COMMENT,page,pagesize);
        //判断是否为空
        if (CollUtil.isEmpty(commentList)){
            return new PageResult(page,pagesize,0,null);
        }
        //获取评论人的ids
        List<Long> ids = commentList.stream().map(Comment::getUserId).collect(Collectors.toList());
        //获取评论人的详细信息
        List<UserInfo> userInfoList = userInfoApi.findByIds(ids);
        //将list集合转换成map集合 key是id value是详细信息对象
        Map<Long, UserInfo> userInfoMap = userInfoList.stream().collect(Collectors.toMap(UserInfo::getId, Function.identity()));
        List<CommentVo> vos = new ArrayList<>();
        //封装到vo中
        for (Comment comment : commentList) {
            UserInfo userInfo = userInfoMap.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);

                String key = Constants.MOVEMENTS_INTERACT_KEY+comment.getPublishId();
                String hashKey = Constants.MOVEMENT_COMMENT_LIKE_HASHKEY +UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key,hashKey)){
                    vo.setHasLiked(1);
                }

                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0,vos);
    }

    //保存评论
    public void saveComment(String movementId, String comment) {
        //判断是否可以评论
        userFreezeService.freezeCheck(UserHolder.getUserId(),"2");
        Comment newComment = new Comment();
        newComment.setPublishId(new ObjectId(movementId));
        newComment.setCommentType(2);
        newComment.setContent(comment);
        newComment.setUserId(UserHolder.getUserId());
        newComment.setCreated(System.currentTimeMillis());
        commentApi.save(newComment);
    }

    //动态点赞
    public Integer like(String movementId) {
        //查询用户是否点赞
        Boolean hasComment =  commentApi.hasComment(movementId,UserHolder.getUserId(),CommentType.LIKE);
        //如果已点赞抛出异常
        if (hasComment){
            throw new BusinessException(ErrorResult.likeError());
        }
        //封装Comment数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);
        //将用户点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");

        return count;
    }

    //取消点赞
    public Integer dislike(String movementId) {
        //查询用户是否点赞
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LIKE);
        //如果没点赞 抛出异常
        if (!hasComment) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //封装Comment数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.remove(comment);
        //删除用户点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);

        return count;
    }

    //动态喜欢
    public Integer love(String movementId) {
        //查询用户是否喜欢
        Boolean hasComment =  commentApi.hasComment(movementId,UserHolder.getUserId(),CommentType.LOVE);
        //如果已点赞抛出异常
        if (hasComment){
            throw new BusinessException(ErrorResult.loveError());
        }
        //封装Comment数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);
        //将用户点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");

        return count;
    }

    //动态取消喜欢
    public Integer unlove(String movementId) {
        //查询用户是否喜欢
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LOVE);
        //如果没喜欢 抛出异常
        if (!hasComment) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //封装Comment数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.remove(comment);
        //删除用户喜欢状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);

        return count;
    }


    //评论点赞
    public Integer commentsLike(String id) {
        //查询评论数据
        Comment comment = commentApi.findById(id);
        //查询用户是否点赞
        String key = Constants.MOVEMENTS_INTERACT_KEY+comment.getPublishId();
        String hashKey = Constants.MOVEMENT_COMMENT_LIKE_HASHKEY +UserHolder.getUserId();
        String redisLike = (String) redisTemplate.opsForHash().get(key, hashKey);
        if (StringUtils.isNotBlank(redisLike)){
            throw new BusinessException(ErrorResult.error());
        }
        //如果没有点赞则把信息存入redis中
        redisTemplate.opsForHash().put(key,hashKey,"1");
        //更新评论的数据添加点赞信息
        Integer count = commentApi.commentLike(comment);
        return count;
    }

    //评论取消点赞
    public Integer commentsDislike(String id) {
        //查询评论数据
        Comment comment = commentApi.findById(id);
        //查询是否点赞
        String key = Constants.MOVEMENTS_INTERACT_KEY+comment.getPublishId();
        String hashKey = Constants.MOVEMENT_COMMENT_LIKE_HASHKEY +UserHolder.getUserId();
        String redisLike = (String) redisTemplate.opsForHash().get(key, hashKey);
        if (StringUtils.isBlank(redisLike)){
            throw new BusinessException(ErrorResult.error());
        }
        //删除redis中的信息
        redisTemplate.opsForHash().delete(key,hashKey);
        //更新评论表中信息
        Integer count = commentApi.commentDislike(comment);
        return count;
    }
}
